package com.engine.query.cmd;

import com.engine.core.dao.CodeResourceMapper;
import com.engine.core.domain.GenTable;
import com.engine.core.gen.Mysql;
import com.engine.core.interceptor.JdbcCommandContext;
import com.engine.core.interceptor.ResponseCommand;
import com.engine.core.rowMapper.JdbcTypeBiz;
import com.engine.core.rowMapper.MappedType;
import com.engine.core.util.JdbcTemplateUtils;
import com.engine.core.util.QueryUtil;
import com.engine.core.util.Response;
import com.engine.core.util.Utils;
import com.engine.system.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GetByIdCommand extends ResponseCommand {

    public GetByIdCommand(User user, Map<String, Object> params) {
        super(user, params);
    }

    /**
     * @param commandContext
     * @return
     */
    @Override
    public Response execute(JdbcCommandContext commandContext) throws Exception {
        Map<Integer, String>  typeFormat=commandContext.getGlobal().getTypeFormat();
        JdbcTemplate jdbcTemplate=commandContext.getJdbcTemplate();
        CodeResourceMapper codeResourceMapper=commandContext.getApplicationContext().getBean(CodeResourceMapper.class);

        String resId=(String)params.get(QueryUtil.QUERY_RESOURCE);
        String columns=Utils.nullDefault((String)params.get(QueryUtil.QUERY_COLUMNS),"*");
        GenTable genTable=codeResourceMapper.getGenTable(Utils.getInt(resId,0));
        String pkColumnName=genTable.getPkColumn().getColumnName();

        Map<String, MappedType> formatMap=new HashMap<>();

        StringBuilder sqlBuilder=new StringBuilder();
        sqlBuilder.append("select ");
        if(StringUtils.isNotBlank(columns)){
            sqlBuilder.append(columns);
        }else{
            sqlBuilder.append(JdbcTypeBiz.getAllColumns(genTable));
        }
        sqlBuilder.append(" from ");
        sqlBuilder.append(genTable.getResourceName());
        sqlBuilder.append(" where ");
        sqlBuilder.append(pkColumnName);
        sqlBuilder.append(" = ?");
        Response response=Response.static_success("执行成功!").set(QueryUtil.QUERY_RESULT_SQL,sqlBuilder.toString());
        try {
           List<Map<String,Object>> returnList=JdbcTemplateUtils.fetchResult(sqlBuilder.toString(),jdbcTemplate,formatMap,typeFormat,
                   new Object[]{Mysql.javaValueByColumnType(genTable.getPkColumn().getColumnType(),(String)params.get(QueryUtil.QUERY_ID))});
           if(returnList.size()>0){
               response.setHasData(true);
               response.set(QueryUtil.QUERY_RESULT,returnList.get(0));
           }else{
               response.setHasData(false);
           }
           return response;
        } catch (Exception e) {
            throw e;
        }
    }
}
